﻿using ServiceStack.Logging;
using System;
using System.IO;
//using HP.HPTRIM.Web.Configuration;

namespace DocuSignPlugin
{


    public class SigningCompleteService : BaseDocuSignService
    {
        private static readonly ILog _log = LogManager.GetLogger(typeof(SigningCompleteService));

        public object Get(SigningComplete request)
        {

            try
            {
                return completeSiging(request);
            }
            catch (Exception ex)
            {
                TrimHelper.UndoCheckout(request.Uri);

                _log.Error(ex.Message, ex);

                return new DSErrorResponse()
                {
                    HideNavigation = true,
                    ResponseStatus = new ServiceStack.ServiceInterface.ServiceModel.ResponseStatus() { Message = ex.Message }
                };
            }

        }

        private object completeSiging(SigningComplete request)
        {
            if (request.Uri == 0)
            {
                throw new Exception("Record Uri missing from 'Signing Complete' URL.");
            }

            if (request.Event == "signing_complete")
            {
                string docExt = "pdf";

                string docName = TrimHelper.getDocName(request.Uri);

                LoginDetails loginDetails = this.TrimHelper.getUserCredentials(Request);
                string envGuid = this.GetEnvGuid(request.Uri);
                string location = Path.Combine(this.ServiceDefaults.UploadBasePath, "DocuSign");


                if (!Directory.Exists(location))
                {
                    Directory.CreateDirectory(location);
                }

                string fileLocation = Docusign.getDocument(loginDetails, envGuid, location, docName, docExt);


                _log.Info("Document was downloaded from DocuDign. Path/Name : " + fileLocation);


                if (File.Exists(fileLocation))
                {

                    bool checkedIn = TrimHelper.checkIn(request.Uri, fileLocation);
                    _log.Info("checkedIn Path/Name : " + checkedIn);

                    if (checkedIn)
                    {
                        return new DSSigningCompleteResponse() { Uri = request.Uri, Url = _appSettings.GetString("docusign.CompletionUrl")};
                    }
                }
                else
                {
                    throw new Exception("Unable to Download the Signed Document from DocuSign.");
                }

            }
            if (request.Event == "cancel")
            {
                throw new Exception("Signing cancelled.");
            }
            else
            {
                throw new Exception("Something Went Wrong and the page was not signed properly.");

            }




        }
    }
}
